package org.catpay.modules.app.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;

@Service("alipayService")
public class AlipayServiceImpl {
	@Value("${APP_ID}")
	private String APP_ID;
	// 商户应用私钥
	@Value("${APP_PRIVATE_KEY}")
	private String APP_PRIVATE_KEY;
	// 应用公钥
	@Value("${APP_PUBLIC_KEY}")
	private String APP_PUBLIC_KEY;
	// 支付宝公钥
	@Value("${ALIPAY_PUBLIC_KEY}")
	private String ALIPAY_PUBLIC_KEY;

	private String CHARSET = "utf-8";

	/**
	 * 
	 * @param body
	 *            商品描述
	 * @param subject
	 *            商品名称
	 * @param outTradeNo
	 *            订单号
	 * @param totalAmount
	 *            总价
	 * @param notifyUrl
	 *            回调地址
	 * @return
	 */
	public String createAlipayOrder(String body, String subject, String outTradeNo, String totalAmount,
			String notifyUrl) {
		// 实例化客户端

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID,
				APP_PRIVATE_KEY, "json", "UTF-8", APP_PUBLIC_KEY, "RSA2");
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.channel
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(body);
		model.setSubject(subject);
		model.setOutTradeNo(outTradeNo);
		model.setTimeoutExpress("30m");
		model.setTotalAmount(totalAmount);
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		request.setNotifyUrl(notifyUrl);
		try {
			// 这里和普通的接口调用不同，使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			System.out.println(response.getBody());// 就是orderString
													// 可以直接给客户端请求，无需再做处理。
			System.out.print(response.isSuccess());
			return response.getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}

		return null;
	}

	public boolean verifyNotify(Map requestParams) {
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		// 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		// boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String
		// publicKey, String charset, String sign_type)
		boolean flag = false;
		try {
			flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2");
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return flag;
	}

	private static String tet(String body, String subject, String outTradeNo, String totalAmount, String notifyUrl)
			throws AlipayApiException {
		// 实例化客户端

		String APP_ID = "2019071965946049";
		String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDPLEsurit7kiui/vce4WWT+hTNR80IMG0eB2fNz4LlAvqlBWJR5LIfhwYq5nTpaiP4QkorPVT+7Z3EGuT3NyfN369Odd3BFYWx9oVBquAHeP9xv+2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hlJuKW7D/sd4Xa45tDS8FzJFnUc9Ce4bqqQhgdeoynJRt/5kTHQqsolUZa/4Sm6mEWbCij778S3EJUzBbQGMIgtSOrKXTveVRUfw0rOJimrwIDAQAB";

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID,
				APP_PRIVATE_KEY, "json", "UTF-8", APP_PUBLIC_KEY, "RSA2");
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.channel
		AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();

		// 封装请求支付信息
		AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
		model.setBody(body);
		model.setSubject(subject);
		model.setOutTradeNo(outTradeNo);
		model.setTimeoutExpress("30m");
		model.setTotalAmount(totalAmount);
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		System.out.println(alipayClient.pageExecute(request).getBody());
		return null;
	}

	private static String tst(String body, String subject, String outTradeNo, String totalAmount, String notifyUrl)
			throws AlipayApiException {
		// 实例化客户端

		String APP_ID = "2019071965946049";
		String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDPLEsurit7kiui/vce4WWT+hTNR80IMG0eB2fNz4LlAvqlBWJR5LIfhwYq5nTpaiP4QkorPVT+7Z3EGuT3NyfN369Odd3BFYWx9oVBquAHeP9xv+2D1Jveetd+pkusgGSSc4wrgCsGwI424Z3qyJUH4fYTlC2MLiJ0PJbTfn4l2lxaZkibGU/3yXszaa/UvID/VB69hQMvoU22b9utghErT+xmj1PPZ9oq+BZB8kQ6MqIqiAu1yvGgK1tomPtdkVcchE4bt465g+9bzSj/6OBTIem4Akg3P36SqxlYA77yEH70g2bUwFbzb4JJZISzHTSsDEC/kuES94QWraqAVSRxAgMBAAECggEBAJ/uwMdzm4vUpq05CUskk8ctuxtSP5z/zWzuKJuAg7sJlrcINgOkekHOedtqd3yt/MCtZBaHTXNTuoRmgrW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Drv8GaiNsesGxj8/mX4a0a4Th2bKYxAdn/TlESNzjs0oBJdBSF";
		String APP_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzyxLLq4re5Irov73HuFlk/oUzUfNCDBtHgdnzc+C5QL6pQViUeSyH4cGKuZ06Woj+EJKKz1U/u2dxBrk9zcnzd+vTnXdwRWFsfaFQargB3j/cb/tg9Sb3nrXfqZLrIBkknOMK4ArBsCONuGd6siVB+H2E5QtjC4idDyW035+JdpcWmZImxlP98l7M2mv1LyA/1QevYUDL6FNtm/brYIRK0/sZo9Tz2faKvgWQfJEOjKiKogLtcrxoCtbaJj7XZFXHIROG7eOuYPvW80o/+jgUyHpuAJINz9+kqsZWAO+8hB+9INm1MBW82+CSWSEsx00rAxAv5LhEveEFq2qgFUkcQIDAQAB";
		// String ALIPAY_PUBLIC_KEY=
		// "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqn4/1ly9pRSIq5l9HY9bUnjm0oZKEIehpNpGmx9ewkd/42s2+g14uCdSlskTLuvmWqi35oJT37zzb9TTQWOa8tHJnvhpTZfrLBZJY/Jr17h0S3UqCz8chBFTct2F8obIZS7+8bTF2U1r/M7XAyMB7LYitUas0Jobb5JCXG6Ak7kcKPFVRvjwKSbEc2YkOaSJQ9bBO8200iC0pss7VPQTY1WmSS22FS2oRiqyextWM+hlJuKW7D/sd4Xa45tDS8FzJFnUc9Ce4bqqQhgdeoynJRt/5kTHQqsolUZa/4Sm6mEWbCij778S3EJUzBbQGMIgtSOrKXTveVRUfw0rOJimrwIDAQAB";

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID,
				APP_PRIVATE_KEY, "json", "UTF-8", APP_PUBLIC_KEY, "RSA2");
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.channel
		AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

		// 封装请求支付信息
		AlipayTradePagePayModel model = new AlipayTradePagePayModel();
		model.setBody(body);
		model.setSubject(subject);
		model.setOutTradeNo(outTradeNo);
		model.setTimeoutExpress("30m");
		model.setTotalAmount(totalAmount);
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		System.out.println(alipayClient.pageExecute(request).getBody());
		return null;
	}

	public static void main(String[] args) {

		// AlipayServiceImpl ap = new AlipayServiceImpl();
		try {
			AlipayServiceImpl.tet("oy", "测试", "O_33553", "0.01", "");
			AlipayServiceImpl.tst("oy", "测试", "O_3443", "0.01", "");
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
